<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="计划名称">
        <el-input v-model="searchForm.planName" placeholder="请输入计划名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增计划</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="listLoading" :data="planList" border stripe highlight-current-row>
      <el-table-column prop="id" label="计划ID" width="80" />
      <el-table-column prop="planName" label="计划名称" width="200" />
      <el-table-column prop="description" width="180" label="计划描述" show-overflow-tooltip />
      <el-table-column label="执行频率" width="150">
        <template slot-scope="scope">
          <el-tag size="small" :type="getCycleType(scope.row.cycleType)">{{ getCycleText(scope.row.cycleType, scope.row.cycleValue) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="开始时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.startDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="endDate" label="结束时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.endDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="creatorName" label="创建人" width="120">
        <template slot-scope="scope">
          {{ scope.row.creatorName || '加载中...' }}
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.created) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope.row.id)">查看详情</el-button>
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
      :current-page="pagination.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="formData.planName" placeholder="请输入计划名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="计划描述" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="请输入计划描述" :rows="3" maxlength="200" />
        </el-form-item>
        <el-form-item label="执行频率类型" prop="cycleType">
          <el-select v-model="formData.cycleType" placeholder="请选择执行频率类型">
            <el-option label="每日" value="1" />
            <el-option label="每周" value="2" />
            <el-option label="每月" value="3" />
            <el-option label="季度" value="4" />
            <el-option label="年度" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="频率值" prop="cycleValue">
          <el-input v-model.number="formData.cycleValue" placeholder="请输入频率值（如1表示每天一次）" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="巡检计划详情" :visible.sync="detailVisible" width="600px">
      <el-form :model="detailData" label-width="120px">
        <el-form-item label="计划ID">
          <el-input v-model="detailData.id" disabled />
        </el-form-item>
        <el-form-item label="计划名称">
          <el-input v-model="detailData.planName" disabled />
        </el-form-item>
        <el-form-item label="计划描述">
          <el-input v-model="detailData.description" type="textarea" disabled :rows="3" />
        </el-form-item>
        <el-form-item label="执行频率">
          <el-input v-model="detailData.cycleText" disabled />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-input v-model="detailData.startDateFormatted" disabled />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-input v-model="detailData.endDateFormatted" disabled />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="detailData.creatorName" disabled />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="detailData.createdFormatted" disabled />
        </el-form-item>
        <el-form-item label="状态">
          <el-tag size="medium" :type="detailData.status === 1 ? 'success' : 'danger'">
            {{ detailData.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import inspectionPlanApi from '@/api/inspection-plan'
import sysUserApi from '@/api/sys-user'
import { mapGetters } from 'vuex'

export default {
  name: 'InspectionPlanList',
  data() {
    return {
      // 数据列表
      planList: [],
      listLoading: false,
      
      // 分页参数
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      
      // 搜索条件
      searchForm: {
        planName: '',
        status: '',
        cycleType: ''
      },
      
      // 对话框状态
      dialogVisible: false,
      detailVisible: false,
      dialogTitle: '',
      
      // 表单数据
      formData: {
        id: '',
        planName: '',
        description: '',
        cycleType: "1",
        cycleValue: 1,
        startDate: '',
        endDate: '',
        status: 1
      },
      
      // 详情数据
      detailData: {},
      
      // 用于缓存用户信息，避免重复请求
      userMap: {},
      
      // 表单验证规则
      formRules: {
        planName: [
          { required: true, message: '请输入计划名称', trigger: 'blur' },
          { max: 50, message: '计划名称不能超过50个字符', trigger: 'blur' }
        ],
        cycleType: [
          { required: true, message: '请选择执行频率类型', trigger: 'change' }
        ],
        cycleValue: [
          { required: true, message: '请输入频率值', trigger: 'blur' },
          { type: 'number', min: 1, message: '频率值必须大于0', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endDate: [
          { required: false, message: '请选择结束时间', trigger: 'change' }
        ]
      }
    }
  },
  
  created() {
    // 初始化加载数据
    this.fetchPlanList()
  },
  
  methods: {
    // 获取巡检计划列表
    async fetchPlanList() {
      this.listLoading = true
      const params = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        ...this.searchForm
      }
      
      try {
        // 使用query方法代替list方法，避免路径参数冲突
        const res = await inspectionPlanApi.query(params)
        this.planList = res.data.records || []
        this.pagination.total = res.data.total || 0
        this.pagination.pageNum = res.data.current || 1
        this.pagination.pageSize = res.data.size || 10
        
        // 为每条记录获取并设置创建人名称
        for (const plan of this.planList) {
          let creatorName = await this.getUserName(plan.creatorId)
       
		  this.$set(plan, 'creatorName', creatorName)
        }
		console.log(this.planList,"巡检计划列表")
      } catch (error) {
        this.$message.error('获取巡检计划列表失败：' + (error.message || '未知错误'))
        console.error('获取巡检计划列表失败:', error)
      } finally {
        this.listLoading = false
      }
    },
    
    // 查询操作
    handleSearch() {
      this.pagination.pageNum = 1
      this.fetchPlanList()
    },
    
    // 重置搜索条件
    handleReset() {
      this.searchForm = {
        planName: '',
        status: '',
        cycleType: ''
      }
      this.pagination.pageNum = 1
      this.fetchPlanList()
    },
    
    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.fetchPlanList()
    },
    
    // 当前页码改变
    handleCurrentChange(current) {
      this.pagination.pageNum = current
      this.fetchPlanList()
    },
    
    // 新增计划
    handleAdd() {
      this.dialogTitle = '新增巡检计划'
      this.formData = {
        id: '',
        planName: '',
        description: '',
        cycleType: '1',
        cycleValue: 1,
        startDate: '',
        endDate: '',
        status: 1
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },
    
    // 编辑计划
    handleEdit(row) {
      this.dialogTitle = '编辑巡检计划'
      // 确保cycleType转换为字符串类型，与下拉选项的值匹配
      this.formData = {
        ...row,
        cycleType: String(row.cycleType)
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },
    
    // 获取用户名称
    async getUserName(userId) {
      if (!userId) return '未知用户'
      
      // 如果缓存中有，直接返回
      if (this.userMap[userId]) {
        return this.userMap[userId]
      }
      
      try {
        const { data } = await sysUserApi.detail(userId)
        // 缓存用户信息
        this.userMap[userId] = data.username || '未知用户'
        return this.userMap[userId]
      } catch (error) {
        console.error('获取用户信息失败:', error)
        return '未知用户'
      }
    },
    
    // 查看详情
    async handleDetail(id) {
      try {
        const res = await inspectionPlanApi.detail(id)
        this.detailData = res.data
        // 添加频率文本和格式化日期
        this.detailData.cycleText = this.getCycleText(res.data.cycleType, res.data.cycleValue)
        this.detailData.startDateFormatted = this.formatDate(res.data.startDate)
        this.detailData.endDateFormatted = this.formatDate(res.data.endDate)
        this.detailData.createdFormatted = this.formatDate(res.data.created)
        // 获取并添加创建人名称
        this.detailData.creatorName = await this.getUserName(res.data.creatorId)
        this.detailVisible = true
      } catch (error) {
        this.$message.error('获取计划详情失败：' + (error.message || '未知错误'))
        console.error('获取计划详情失败:', error)
      }
    },
    
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const data = { ...this.formData }
          let requestPromise
          
          // 验证时间逻辑
      if (data.endDate && new Date(data.startDate) >= new Date(data.endDate)) {
        this.$message.error('结束时间必须晚于开始时间')
        return
      }
          
          if (data.id) {
            requestPromise = inspectionPlanApi.update(data)
          } else {
            // 添加新计划时设置创建者ID和创建时间
            data.creatorId = this.$store.getters.userId || 1
            data.created = new Date()
			console.log('data:', data)
            requestPromise = inspectionPlanApi.add(data)
          }
          
          requestPromise.then(() => {
            this.dialogVisible = false
            this.$message.success('保存成功')
            this.fetchPlanList()
          }).catch(error => {
            this.$message.error('保存失败：' + (error.message || '未知错误'))
            console.error('保存巡检计划失败:', error)
          })
        }
      })
    },
    
    // 删除计划
    handleDelete(id) {
      this.$confirm('确定要删除该巡检计划吗？删除后无法恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        inspectionPlanApi.delete(id).then(() => {
          this.$message.success('删除成功')
          this.fetchPlanList()
        }).catch(error => {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
          console.error('删除巡检计划失败:', error)
        })
      }).catch(() => {
        // 取消删除操作
      })
    },
    
    // 更改状态
    handleStatusChange(row) {
      const status = row.status
      inspectionPlanApi.enable({
        id: row.id,
        status: status
      }).then(() => {
        this.$message.success('状态更新成功')
      }).catch(error => {
        // 恢复原状态
        row.status = status === 1 ? 0 : 1
        this.$message.error('状态更新失败：' + (error.message || '未知错误'))
        console.error('更新状态失败:', error)
      })
    },
    
    // 获取周期文本
    getCycleText(cycleType, cycleValue) {
      const cycleTypeMap = {
        '1': '每日',
        '2': '每周',
        '3': '每月',
        '4': '季度',
        '5': '年度'
      }
      return `${cycleValue}次 ${cycleTypeMap[cycleType] || '未知'}`
    },
    
    // 获取周期标签类型
    getCycleType(cycleType) {
      const typeMap = {
        '1': 'primary',
        '2': 'success',
        '3': 'warning',
        '4': 'info',
        '5': 'danger'
      }
      return typeMap[cycleType] || 'default'
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      if (isNaN(date.getTime())) return ''
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
  },
  computed: {
    ...mapGetters(['userId'])
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>